//
//  WBUserAccount.swift
//  weibo
//
//  Created by Felix on 16/11/15.
//  Copyright © 2016年 Felix. All rights reserved.
//

import UIKit

class WBUserAccount: NSObject,NSCoding {
    
    
    ///令牌
    var access_token:String?
    
    
    ///还有多少秒过期
    var expires_in:Int = 0{
        didSet{
            expires_date = NSDate.init(timeIntervalSinceNow: TimeInterval.init(expires_in))
        }
    }
    
    ///用户id
    var uid:String?
    
    ///真正过期时间
    var expires_date:NSDate?
    
    ///  用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    /// 用户昵称
    var screen_name: String?
    
    
    ///MARK:-生命周期方法
    init(dict:[String:Any]) {
        super.init()
        self.setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    
    override var description: String{
        let keys = ["access_token","expires_in","uid","expires_date","avatar_large","screen_name"]
        let  dict = dictionaryWithValues(forKeys: keys)
        return "\(dict)"
        
    }
    
    
    
    
    //MARK:- 外部控制方法
    
    //保存用户数据
    func saveAccount() -> Bool {
        return NSKeyedArchiver.archiveRootObject(self, toFile: WBUserAccount.filePath)
    }
    
    //解归档
    class func loadUserAccount() -> WBUserAccount? {
        if WBUserAccount.userAccount != nil {
            return WBUserAccount.userAccount
        }
        
        guard let account = NSKeyedUnarchiver.unarchiveObject(withFile: WBUserAccount.filePath) as? WBUserAccount else {
            return nil
        }
        
        guard let date = account.expires_date  else {
            return nil
        }
        AdaLog(message: date)
        
        if date.compare(NSDate.init() as Date) == ComparisonResult.orderedAscending {
            AdaLog(message: "过期了")
            return nil
        }
        
        WBUserAccount.userAccount = account
        return WBUserAccount.userAccount
        
    }
    
    
    //是否登陆
    class func isLoggin() -> Bool{
        return WBUserAccount.loadUserAccount() != nil
    }
    
    //加载用户信息
    func  loadUserInfo(finished:@escaping (_ account:WBUserAccount? , _ error:NSError?) ->()) {
        assert(access_token != nil, "使用前需先授权")
        
        // 1.准备请求路径
        let path = "2/users/show.json"
        // 2.准备请求参数
        let parameters = ["access_token": access_token!, "uid": uid!]
        // 3.发送GET请求
        WBNetWorkTool.shareInstance.get(path, parameters: parameters, progress: { (progress:Progress) in
            
            }, success: { (task:URLSessionDataTask, objc:Any?) in
                let dict = objc as! [String:Any]
                self.avatar_large = dict["avatar_large"] as? String
                self.screen_name = dict["screen_name"] as? String
                finished(self, nil)
        }) { (task:URLSessionDataTask?, error:Error) in
                finished(nil, error as NSError)
        }
    }
    
    
    //定义一个用户账户
    static var userAccount:WBUserAccount?
    //定义一个用户账户存储路径
    static let filePath = "userAccount.plist".cacheDir()
    
    
    //MARK:- NSCoding
    public func encode(with aCoder: NSCoder){
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(expires_date, forKey: "expires_date")
        aCoder.encode(avatar_large, forKey: "avatar_large")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(screen_name, forKey: "screen_name")
    }
    
    public required init?(coder aDecoder: NSCoder){
        self.access_token = aDecoder.decodeObject(forKey: "access_token") as! String?
        self.expires_in = aDecoder.decodeInteger(forKey: "expires_in")
        self.expires_date = aDecoder.decodePropertyList(forKey: "expires_date") as! NSDate?
        self.uid = aDecoder.decodeObject(forKey: "uid") as! String?
        self.avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as! String?
        self.screen_name = aDecoder.decodeObject(forKey: "screen_name")as! String?
        
    }
    
    
    
}
